#!/usr/bin/env ruby

# Executar: cat files.txt | xargs  ruby 2k_fact.rb

y = {}
yi = []
r = 768
k = 3

q0_vector = [1,1,1,1,1,1,1,1]
qt_vector = [-1,1,-1,1,-1,1,-1,1]
qn_vector = [-1,-1,1,1,-1,-1,1,1]
qh_vector = [-1,-1,-1,-1,1,1,1,1]

# input com os arquivos de todas as 8 configuracoes
i = 0
ARGV.each do |input|
  tmp = File.new(input, 'r')
  y[i] = []
  tmp.each do |line|
    y[i] << line.strip.to_f
  end
  yi << y[i].inject{ |sum, el| sum + el }.to_f / y[i].size
  i += 1
end

qtn_vector = []
qth_vector = []
qnh_vector = []
qtnh_vector = []

8.size.times do |i|
  qtn_vector << qt_vector[i] * qn_vector[i]
  qth_vector << qt_vector[i] * qh_vector[i]
  qnh_vector << qn_vector[i] * qh_vector[i]
  qtnh_vector << qt_vector[i] * qn_vector[i] * qh_vector[i]
end

q0 = 0
qt = 0
qn = 0
qh = 0
qtn = 0
qth = 0
qnh = 0
qtnh = 0

8.size.times do |i|
  q0 += q0_vector[i] * yi[i]
  qt += qt_vector[i] * yi[i]
  qn += qn_vector[i] * yi[i]
  qh += qh_vector[i] * yi[i]
  qtn += qtn_vector[i] * yi[i]
  qth += qth_vector[i] * yi[i]
  qnh += qnh_vector[i] * yi[i]
  qtnh += qtnh_vector[i] * yi[i]
end

q0 = q0/8
qt = qt/8
qn = qn/8
qh = qh/8
qtn = qtn/8
qth = qth/8
qnh = qnh/8
qtnh = qtnh/8
puts ""

ssy = 0

y.keys.each do |key|
  samples = y[key]
  samples.each do|e|
    ssy += e**2
  end
end

sse = 0
y.keys.each do |key|
  mean = yi[key]
  samples = y[key]
  samples.each do |e|
    sse += (e - mean)**2
  end
end

ss_0 = 2**k * r * q0**2
ss_t = 2**k * r * qt**2
ss_n = 2**k * r * qn**2
ss_h = 2**k * r * qh**2
ss_tn = 2**k * r * qtn**2
ss_th = 2**k * r * qth**2
ss_nh = 2**k * r * qnh**2
ss_tnh = 2**k * r * qtnh**2

sst = ss_t + ss_n + ss_h + ss_tn + ss_th + ss_nh + ss_tnh + sse

######################################################

puts "q0 => #{q0}"
puts "qt => #{qt}"
puts "qn => #{qn}"
puts "qh => #{qh}"
puts "qtn => #{qtn}"
puts "qth => #{qth}"
puts "qnh => #{qnh}"
puts "qtnh => #{qtnh}"
puts ""

puts ""
puts "ssy => #{ssy}"
puts "sse => #{sse}"
puts "sst => #{sst}"

puts ""
puts "ss(t) => #{100*ss_t/sst}"
puts "ss(n) => #{100*ss_n/sst}"
puts "ss(h) => #{100*ss_h/sst}"
puts "ss(tn) => #{100*ss_tn/sst}"
puts "ss(th) => #{100*ss_th/sst}"
puts "ss(nh) => #{100*ss_nh/sst}"
puts "ss(tnh) => #{100*ss_tnh/sst}"
puts "sse => #{100*sse/sst}"
